<!-- 检查项管理-卡片页 -->
<template>
  <view class="s-list">
    <Header title="检查项管理" bgColor="#fff" :leftIconSize="20"/>
    <Tabs :list="tabsList" @changeTab="changeTab"/>
    <!-- 主内容 -->
    <view class='s-list-main'>
      <scroll-view scroll-y="true" refresher-enabled="true" :refresher-triggered="triggered" :lower-threshold="50"
                   :style="{height: '100%'}" @scrolltolower="nextPage" :refresher-threshold="80"
                   refresher-background="rgb(244, 244, 244)" @refresherpulling="onPulling" @refresherrefresh="onRefresh"
                   @refresherrestore="onRestore" @refresherabort="onAbort">
        <view v-if="dataList.length > 0" class="indic-swipe">
          <view class="uv-swipe-action-item li-overflow" v-for="(item,index) in dataList" :key="index">
            <view class="indic-box">
              <view class='l-title'>
                <view class="l-title-num">{{ index + 1 }}</view>
                <view class="l-title-text">{{ item.content }}</view>
                <view class="l-title-icon" v-if="item.children && item.children.length > 0" @click="childToggle(index)">
                  <uv-icon name="arrow-down" size="36rpx" color="#000000" v-if="item.childShow"/>
                  <uv-icon name="arrow-right" size="36rpx" color="#000000" v-else/>
                </view>
              </view>
              <view class='s-row'>
                <text>排序：</text>
                {{ item.sort !== null ? item.sort : '--' }}
              </view>
              <view class='s-row'>
                <text>更新时间：</text>
                {{ proxy.dayjs(item.updateDate).format('YYYY-MM-DD HH:mm:ss') }}
              </view>
              <view class='s-btn-group'>
                <uv-button type="info" plain text="添加子检查项" @click="addFun(item)"/>
                <uv-button type="info " plain text="编辑" @click="editFun(item)"/>
                <uv-button type="error" plain text="删除" @click="deleteFun(item)"/>
              </view>
              <view v-for="(itemB,indexB) in item.children" :key="indexB" v-if="item.childShow">
                <view class="li-line"></view>
                <view class='l-title'>
                  <view class="l-title-num">{{ index + 1 }}.{{ indexB + 1 }}</view>
                  <view class="l-title-text">{{ itemB.content }}</view>
                </view>
                <view class='s-row'>
                  <text>排序：</text>
                  {{ itemB.sort !== null ? itemB.sort : '--' }}
                </view>
                <view class='s-row'>
                  <text>更新时间：</text>
                  {{ proxy.dayjs(itemB.updateDate).format('YYYY-MM-DD HH:mm:ss') }}
                </view>
                <view class='s-btn-group'>
                  <uv-button type="info" plain text="编辑" @click="editFun(itemB)"/>
                  <uv-button type="error" plain text="删除" @click="deleteFun(itemB)"/>
                </view>
              </view>
            </view>
          </view>
          <uni-load-more :status="loadingType" :content-text="contentText"/>
        </view>
        <view v-if="emptyFlag" class="empty-box">
          <uv-empty mode="data" icon="/static/image/no-data.png" width="200rpx" height="260rpx" text="&nbsp;"/>
        </view>
      </scroll-view>
    </view>
    <!-- 底部按钮 -->
    <view class='s-btn-common'>
      <uv-button type="primary" text="添加" @click="addFun(queryForm)"/>
      <uv-button v-if="userInfo.user.org.parentId !== '0'" type="primary" class="li-ml" text="引用上级检查项" @click="quoteSuperior()"/>
    </view>
  </view>
</template>

<script setup>
  import entryAPI from '@/api/law/entry/entry';
  import {onLoad} from '@dcloudio/uni-app';
  import {reactive, ref, getCurrentInstance} from 'vue';

  const {proxy} = getCurrentInstance();
  const tabsCurrent = ref('食品安全');
  let tabsList = ref([
    {
      id: '1',
      name: '食品安全',
    }, {
      id: '2',
      name: '校园安全',
    }, {
      id: '3',
      name: '食堂自查'
    }, {
      id: '4',
      name: '校园自查'
    }, {
      id: '5',
      name: '配餐单位自查'
    }, {
      id: '6',
      name: '配餐单位安全'
    },
  ]);
  let pcoTabList = ref([
    {
      id: '7',
      name: '有害生物检查'
    }, {
      id: '8',
      name: '有害生物自查'
    }
  ]);
  let userInfo = ref(uni.getStorageSync('userInfo'));
  console.log(userInfo.value)
  const queryForm = reactive({ // 查询条件
    pageSize: 10,
    pageNum: 1,
    parentId: '',
    parentName: '',
    content: '',
    entryType: '1',
    createOrgId: userInfo.value.user.orgId,
  });
  const dataList = reactive([]);
  const total = ref(0);
  const freshing = ref(false);
  const triggered = ref(false);
  const emptyFlag = ref(false);
  const loadingType = ref('noMore');
  const contentText = reactive({
    contentdown: "上拉显示更多",
    contentrefresh: "正在加载...",
    contentnomore: "没有更多数据了"
  });

  /** 数据加载 */
  onLoad(async () => {
    initTabList();
    searchList();
  });

  // 初始化tabs列表
  let initTabList = () => {
    userInfo.value.permissions.find(item => {
      if (item === 'iot:send:jyj') {
        tabsList.value = pcoTabList.value
        tabsCurrent.value = '有害生物检查';
        queryForm.entryType = '7';
      }
    })
  }

  /** 搜索数据列表 */
  let searchList = () => {
    queryForm.pageNum = 1;
    getListData();
  };

  /** 获取数据列表 */
  let getListData = async () => {
    let res = await proxy.http.asyncPost(entryAPI.entryTreeList, queryForm);
    if (res.code === 0) {
      total.value = res.data.total;
      if (queryForm.pageNum === 1) {
        dataList.length = 0;
      }
      dataList.push(...res.data);
      if (dataList.length < total.value) {
        loadingType.value = 'more';
      } else {
        loadingType.value = 'noMore'; //没有数据时显示‘没有更多’
      }
      emptyFlag.value = dataList.length <= 0;
    } else {
      await uni.showToast({title: res.msg, icon: 'none'});
    }
  };

  /** 点击tab切换 */
  function changeTab(e) {
    tabsCurrent.value = e.name;
    queryForm.entryType = e.id;
    searchList();
  }

  /** 卡片是否展开 */
  function childToggle(index) {
    dataList[index].childShow = !dataList[index].childShow
  }

  /** 添加 */
  const addFun = (e) => {
    uni.navigateTo({
      url: '/packageBase/pages/checkManage/checkManageAdd?row=' + encodeURIComponent(JSON.stringify(e)),
      success: () => {
        uni.$once("refresh", () => {
          searchList();
        });
      },
    });
  };

  /** 编辑 */
  const editFun = (e) => {
    uni.navigateTo({
      url: '/packageBase/pages/checkManage/checkManageAdd?row=' + encodeURIComponent(JSON.stringify(e)) + '&editFlag=' + true,
      success: () => {
        uni.$once("refresh", () => {
          searchList();
        });
      },
    });
  };

  /** 引用上级检查项 */
  const quoteSuperior = () => {
    uni.navigateTo({
      url: '/packageBase/pages/checkManage/checkManageQuote?entryType=' + queryForm.entryType + '&title=' + tabsCurrent.value + '引用检查项',
      success: () => {
        uni.$once("refresh", () => {
          searchList();
        });
      },
    });
  };

  /** 删除 */
  const deleteFun = (e) => {
    uni.showModal({
      title: '提示',
      // 提示文字
      content: '确认删除该条指标？',
      // 取消按钮的文字自定义
      cancelText: "取消",
      // 确认按钮的文字自定义
      confirmText: "删除",
      //删除字体的颜色
      confirmColor: 'red',
      //取消字体的颜色
      cancelColor: '#000000',
      success: async function (res) {
        if (res.confirm) {
          let res = await proxy.http.asyncPost(entryAPI.entryRemoveById(e.id));
          if (res.code === 0) {
            await uni.showToast({
              title: '删除成功',
              icon: 'success',
              duration: 2000
            })
            setTimeout(function () {
              getListData();
            }, 1000);
          } else {
            await uni.showToast({title: res.msg, icon: 'none'});
          }
        }
      }
    });
  };

  /** 滚动视图区域 */
  // 翻页
  let nextPage = () => {
    if (queryForm.pageNum * queryForm.pageSize < total.value) {
      queryForm.pageNum++;
      getListData()
    }
  };
  // 下拉
  let onPulling = () => {
    freshing.value = false;
    setTimeout(() => {
      triggered.value = true;
    }, 1000)
  };
  // 刷新
  let onRefresh = () => {
    if (freshing.value) return;
    triggered.value = 'restore';
    setTimeout(() => {
      freshing.value = false;
      triggered.value = false;
    }, 1000)
    //获取数据的函数
    queryForm.pageNum = 1 // 记录数
    getListData()
  };
  let onRestore = () => {
    triggered.value = 'restore'; // 需要重置
  };
  let onAbort = () => {
    console.log("onAbort");
  };
</script>

<style scoped lang="scss">
  ::v-deep .indic-box .s-btn-group .uv-button--plain.uv-button--info {
    color: #000000 !important;
  }
  ::v-deep .uv-button--plain.uv-button--error {
    color: #F53F3F !important;
  }
  ::v-deep .uv-icon--right {
    margin-top: 4rpx;
  }
</style>
